package cn.yhsx.jenkins.plugins.rotator;

import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractProject;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import jenkins.tasks.SimpleBuildStep;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;

import javax.annotation.Nonnull;
import java.io.IOException;

/**
 * insert params into the environment
 *
 * @author slf
 * @since 2021/12/30 16:44
 */
public class RotatorParamSetBuilder extends Builder implements SimpleBuildStep {

    private final String key;
    private final String value;

    @DataBoundConstructor
    public RotatorParamSetBuilder(String key, String value) {
        this.key = key;
        this.value = value;
    }


    public String getKey() {
        return key;
    }

    public String getValue() {
        return value;
    }

    @Override
    public void perform(Run<?, ?> run, FilePath workspace, EnvVars env, Launcher launcher,
                        TaskListener listener)
            throws InterruptedException, IOException {
        RotatorAction action = run.getAction(RotatorAction.class);
        if (action == null) {
            return;
        }
        String key1, value1;
        if (key == null || value == null || (key1 = env.expand(key)) == null
                || (value1 = env.expand(value)) == null) {
            listener.error("key or value is null");
            run.setResult(Result.FAILURE);
            return;
        }
        action.getCurrent().addParameter(key1, env.expand(value));
    }


    @Extension
    @Symbol("rotatorParamSet")
    public static class DescriptorImpl extends BuildStepDescriptor<Builder> {

        @Nonnull
        @Override
        public String getDisplayName() {
            return Messages.RotatorParamSetBuilder_displayName();
        }

        @Override
        public boolean isApplicable(Class<? extends AbstractProject> jobType) {
            return true;
        }
    }

}